package view;

import com.toedter.calendar.JDateChooser;
import model.Grade;
import model.Subject;
import model.User;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.category.DefaultCategoryDataset;
import service.GradeService;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;
import java.awt.*;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;
import model.StudentProfile;

import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
import utils.DatabaseUtil;
import java.awt.Color;

import org.jfree.chart.plot.PiePlot;

import java.sql.PreparedStatement;
import javax.swing.table.DefaultTableCellRenderer;

public class GradeAnalysisPanel extends JPanel {
    private static final Font TITLE_FONT = new Font("微软雅黑", Font.BOLD, 14);
    private static final Font CONTENT_FONT = new Font("微软雅黑", Font.PLAIN, 13);
    
    private User currentUser;
    private GradeService gradeService;
    private JTable gradeTable;
    private DefaultTableModel tableModel;
    private JPanel chartPanel;
    private ChartPanel barChartPanel;
    private ChartPanel pieChartPanel;
    private ChartPanel lineChartPanel;
    private JComboBox<String> classComboBox;
    private JComboBox<String> examTypeComboBox;
    private JDateChooser examDateChooser;
    private JTextField searchField;
    private JComboBox<String> sortComboBox;
    private Map<String, Integer> classIdMap = new HashMap<>();
    private boolean isClassTeacher = false;
    private List<Subject> classSubjects;
    private JPanel statsPanel;
    private JToggleButton viewToggleButton;
    private CardLayout cardLayout;
    private JPanel mainPanel;
    private JPanel classTeacherPanel;
    private JPanel teacherPanel;
    private JComboBox<String> departmentComboBox;  // 系部选择
    private JComboBox<String> majorComboBox;       // 专业选择
    private Map<String, Integer> departmentIdMap = new HashMap<>();
    private Map<String, Integer> majorIdMap = new HashMap<>();
    private boolean isAdmin;
    private JLabel totalStudentsLabel;
    private JLabel averageScoreLabel;
    private JLabel passRateLabel;
    private JLabel excellentRateLabel;
    
    private Map<String, List<Grade>> gradeCache = new HashMap<>();
    
    public GradeAnalysisPanel(User currentUser) {
        this.currentUser = currentUser;
        this.gradeService = new GradeService();
        this.isAdmin = "ADMIN".equals(currentUser.getRole());
        
        setLayout(new BorderLayout());
        
        // 根据用户角色初始化不同的视图
        if (isAdmin) {
            // 管理员视图
            add(createAdminPanel(), BorderLayout.CENTER);
            // 加载初始数据
            loadDepartments();
            refreshData();
        }
    }

    private void refreshData() {
        if (isAdmin) {
            // 管理员视图的刷新逻辑
            Map<String, Object> filters = new HashMap<>();
            
            if (departmentComboBox != null) {
                String selectedDept = (String) departmentComboBox.getSelectedItem();
                if (selectedDept != null && !selectedDept.equals("全部系部")) {
                    filters.put("department", selectedDept);
                }
            }
            
            if (majorComboBox != null) {
                String selectedMajor = (String) majorComboBox.getSelectedItem();
                if (selectedMajor != null && !selectedMajor.equals("全部专业")) {
                    filters.put("major", selectedMajor);
                }
            }
            
            if (classComboBox != null) {
                String selectedClass = (String) classComboBox.getSelectedItem();
                if (selectedClass != null && !selectedClass.equals("全部班级")) {
                    filters.put("className", selectedClass);
                }
            }
            
            if (examTypeComboBox != null) {
                String selectedExamType = (String) examTypeComboBox.getSelectedItem();
                if (selectedExamType != null && !selectedExamType.equals("全部")) {
                    filters.put("examType", selectedExamType);
                }
            }
            
            // 加载成绩数据
            loadGradeData(filters);
            
            // 更新统计信息
            Map<String, Object> stats = gradeService.getGradeStats(filters);
            updateStatistics(stats);
            updateCharts(stats);
        } else {
            // 教师视图的刷新逻辑
            if (isClassTeacher) {
                if (viewToggleButton != null && viewToggleButton.isSelected()) {
                    loadNormalData(); // 加载任教视图数据
                } else {
                    loadClassTeacherData(); // 加载班级视图数据
                }
            } else {
                loadNormalData();
            }
        }
    }

    private void updateStatistics(Map<String, Object> filters) {
        if (filters == null) return;
        
        DecimalFormat df = new DecimalFormat("0.00");
        
        int totalCount = (int) filters.get("totalCount");
        double avgScore = (double) filters.get("avgScore");
        double passRate = (double) filters.get("passRate");
        double excellentRate = (double) filters.get("excellentRate");
        
        totalStudentsLabel.setText("总人数: " + totalCount + "人");
        averageScoreLabel.setText("平均分: " + df.format(avgScore));
        passRateLabel.setText("及格率: " + df.format(passRate) + "%");
        excellentRateLabel.setText("优秀率: " + df.format(excellentRate) + "%");
    }

    private ChartPanel createPieChartPanel() {
        DefaultPieDataset dataset = new DefaultPieDataset();
        JFreeChart chart = ChartFactory.createPieChart(
            "成绩等级分布",      // 图表标题
            dataset,
            true,             // 显示图例
            true,             // 显示工具提示
            false             // 不生成URL
        );
        
        // 设置图表样式
        chart.setTitle(new TextTitle("成绩等级分布", new Font("微软雅黑", Font.BOLD, 14)));
        PiePlot plot = (PiePlot) chart.getPlot();
        plot.setBackgroundPaint(Color.WHITE);
        plot.setLabelFont(new Font("微软雅黑", Font.PLAIN, 12));
        
        // 设置饼图颜色
        plot.setSectionPaint("优秀", new Color(91, 155, 213));
        plot.setSectionPaint("良好", new Color(112, 173, 71));
        plot.setSectionPaint("不及格", new Color(237, 125, 49));
        
        // 设置图例字体
        chart.getLegend().setItemFont(new Font("微软雅黑", Font.PLAIN, 12));
        
        ChartPanel chartPanel = new ChartPanel(chart);
        chartPanel.setPreferredSize(new Dimension(400, 300));
        return chartPanel;
    }
    
    private void updateCharts(Map<String, Object> stats) {
        if (stats == null || chartPanel == null) return;
        
        // 更新饼图
        DefaultPieDataset pieDataset = new DefaultPieDataset();
        pieDataset.setValue("90-100分", getIntValue(stats.get("range_90_100")));
        pieDataset.setValue("80-89分", getIntValue(stats.get("range_80_89")));
        pieDataset.setValue("70-79分", getIntValue(stats.get("range_70_79")));
        pieDataset.setValue("60-69分", getIntValue(stats.get("range_60_69")));
        pieDataset.setValue("60分以下", getIntValue(stats.get("range_0_59")));
        
        JFreeChart pieChart = ChartFactory.createPieChart(
            "成绩分布",  // 图表标题
            pieDataset,
            true,       // 显示图例
            true,
            false
        );
        
        // 设置饼图样式
        PiePlot plot = (PiePlot) pieChart.getPlot();
        plot.setLabelFont(new Font("微软雅黑", Font.PLAIN, 12));
        plot.setLabelGap(0.02);
        
        // 设置标题字体
        pieChart.getTitle().setFont(new Font("微软雅黑", Font.BOLD, 16));
        // 设置图例字体
        pieChart.getLegend().setItemFont(new Font("微软雅黑", Font.PLAIN, 12));
        
        // 设置背景色
        plot.setBackgroundPaint(Color.WHITE);
        pieChart.setBackgroundPaint(Color.WHITE);
        
        if (pieChartPanel != null) {
            pieChartPanel.setChart(pieChart);
        }
        
        // 更新柱状图
        DefaultCategoryDataset barDataset = new DefaultCategoryDataset();
        barDataset.addValue(getIntValue(stats.get("range_90_100")), "人数", "90-100分");
        barDataset.addValue(getIntValue(stats.get("range_80_89")), "人数", "80-89分");
        barDataset.addValue(getIntValue(stats.get("range_70_79")), "人数", "70-79分");
        barDataset.addValue(getIntValue(stats.get("range_60_69")), "人数", "60-69分");
        barDataset.addValue(getIntValue(stats.get("range_0_59")), "人数", "60分以下");
        
        JFreeChart barChart = ChartFactory.createBarChart(
            "成绩分布",     // 图表标题
            "分数段",       // x轴标签
            "人数",         // y轴标签
            barDataset,
            PlotOrientation.VERTICAL,
            true,          // 显示图例
            true,
            false
        );
        
        // 设置字体
        barChart.getTitle().setFont(new Font("微软雅黑", Font.BOLD, 16));
        barChart.getLegend().setItemFont(new Font("微软雅黑", Font.PLAIN, 12));
        
        CategoryPlot barPlot = barChart.getCategoryPlot();
        barPlot.getDomainAxis().setLabelFont(new Font("微软雅黑", Font.PLAIN, 12));
        barPlot.getDomainAxis().setTickLabelFont(new Font("微软雅黑", Font.PLAIN, 12));
        barPlot.getRangeAxis().setLabelFont(new Font("微软雅黑", Font.PLAIN, 12));
        barPlot.getRangeAxis().setTickLabelFont(new Font("微软雅黑", Font.PLAIN, 12));
        
        // 设置背景色
        barPlot.setBackgroundPaint(Color.WHITE);
        barChart.setBackgroundPaint(Color.WHITE);
        
        if (barChartPanel != null) {
            barChartPanel.setChart(barChart);
        }
        
        // 刷新显示
        chartPanel.revalidate();
        chartPanel.repaint();
    }
    
    private int getIntValue(Object value) {
        if (value == null) return 0;
        if (value instanceof Number) {
            return ((Number) value).intValue();
        }
        try {
            return Integer.parseInt(value.toString());
        } catch (NumberFormatException e) {
            return 0;
        }
    }

    private void createClassTeacherTable() {
        System.out.println("Creating class teacher table...");
        
        // 创建动态列
        Vector<String> columnNames = new Vector<>();
        columnNames.add("学号");
        columnNames.add("姓名");
        
        // 添加所有科目列
        if (classSubjects != null && !classSubjects.isEmpty()) {
            for (Subject subject : classSubjects) {
                columnNames.add(subject.getSubjectName() + "(学分:" + subject.getCredits() + ")");
                System.out.println("Adding subject column: " + subject.getSubjectName());
            }
        } else {
            System.out.println("Warning: No subjects found for class teacher table");
        }
        
        // 添加统计列
        columnNames.add("平均分");
        columnNames.add("总分");
        columnNames.add("总学分");
        
        System.out.println("Creating table with " + columnNames.size() + " columns");
        
        // 使用 Vector 创建表格模型
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
            
            @Override
            public Class<?> getColumnClass(int columnIndex) {
                if (columnIndex >= 2 && columnIndex < getColumnCount() - 3) {
                    return Double.class; // 成绩列使用 Double 类型
                }
                return Object.class;
            }
        };
        
        gradeTable = new JTable(tableModel);
        gradeTable.setFont(CONTENT_FONT);
        gradeTable.getTableHeader().setFont(TITLE_FONT);
        
        // 设置表格列宽和对齐方式
        TableColumnModel columnModel = gradeTable.getColumnModel();
        columnModel.getColumn(0).setPreferredWidth(100);  // 学号
        columnModel.getColumn(1).setPreferredWidth(80);   // 姓名
        
        // 设置其他列的宽度和对齐方式
        for (int i = 2; i < columnModel.getColumnCount(); i++) {
            columnModel.getColumn(i).setPreferredWidth(100);
            DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
            renderer.setHorizontalAlignment(JLabel.CENTER);
            gradeTable.getColumnModel().getColumn(i).setCellRenderer(renderer);
        }
        
        // 打印列信息
        System.out.println("Table created with following columns:");
        for (int i = 0; i < tableModel.getColumnCount(); i++) {
            System.out.println(i + ": " + tableModel.getColumnName(i));
        }
    }
    
    private void loadClassTeacherData() {
        if (tableModel == null) {
            System.out.println("Error: Table model is null");
            return;
        }
        
        System.out.println("Starting to load class teacher data...");
        System.out.println("Table column count: " + tableModel.getColumnCount());
        tableModel.setRowCount(0);
        Map<String, Object> filters = getFilters();
        
        // 首先获取班级所有学生
        List<StudentProfile> students = getClassStudents();
        System.out.println("Found " + students.size() + " students");
        
        // 获取班级所有成绩
        List<Grade> grades = gradeService.getClassGrades(currentUser.getId(), filters);
        System.out.println("Found " + grades.size() + " grades");
        
        // 按学生分组处理成绩
        Map<String, Map<String, Grade>> studentGrades = new HashMap<>();
        for (Grade grade : grades) {
            System.out.println("Processing grade: Student=" + grade.getStudentNo() + 
                             ", Subject=" + grade.getSubjectName() + 
                             ", Score=" + grade.getScore());
            studentGrades.computeIfAbsent(grade.getStudentNo(), k -> new HashMap<>())
                        .put(grade.getSubjectName(), grade);
        }
        
        // 统计数据
        int totalCount = students.size();
        int passCount = 0;
        int excellentCount = 0;
        int range90_100 = 0;
        int range80_89 = 0;
        int range70_79 = 0;
        int range60_69 = 0;
        int range0_59 = 0;
        
        // 计算各科目平均分
        Map<String, Double> subjectAverages = new HashMap<>();
        Map<String, Integer> subjectCounts = new HashMap<>();
        
        // 遍历所有成绩，计算每个科目的总分和人数
        for (Grade grade : grades) {
            String subjectName = grade.getSubjectName();
            subjectAverages.merge(subjectName, grade.getScore(), Double::sum);
            subjectCounts.merge(subjectName, 1, Integer::sum);
        }
        
        // 计算每个科目的平均分
        for (String subject : subjectAverages.keySet()) {
            double total = subjectAverages.get(subject);
            int count = subjectCounts.get(subject);
            subjectAverages.put(subject, total / count);
        }
        
        // 填充表格数据
        for (StudentProfile student : students) {
            List<Object> rowData = new ArrayList<>();
            String studentNo = student.getStudentNo();
            Map<String, Grade> subjectGrades = studentGrades.getOrDefault(studentNo, new HashMap<>());
            
            // 添加学号和姓名
            rowData.add(studentNo);
            rowData.add(student.getName());
            
            // 计算统计数据
            double totalScore = 0;
            double totalCredits = 0;
            int validSubjectCount = 0;
            
            // 添加各科成绩
            if (classSubjects != null && !classSubjects.isEmpty()) {
                for (Subject subject : classSubjects) {
                    Grade grade = subjectGrades.get(subject.getSubjectName());
                    if (grade != null) {
                        double score = grade.getScore();
                        rowData.add(score);
                        totalScore += score;
                        validSubjectCount++;
                        
                        // 统计成绩分布
                        if (score >= 90) {
                            range90_100++;
                            excellentCount++;
                            passCount++;
                        } else if (score >= 80) {
                            range80_89++;
                            passCount++;
                        } else if (score >= 70) {
                            range70_79++;
                            passCount++;
                        } else if (score >= 60) {
                            range60_69++;
                            passCount++;
                        } else {
                            range0_59++;
                        }
                        
                        // 只有及格的成绩才计入学分
                        if (score >= 60) {
                            totalCredits += subject.getCredits();
                        }
                    } else {
                        rowData.add("-");
                    }
                }
            }
            
            // 添加统计数据
            double avgScore = validSubjectCount > 0 ? totalScore / validSubjectCount : 0;
            rowData.add(String.format("%.2f", avgScore));
            rowData.add(String.format("%.2f", totalScore));
            rowData.add(String.format("%.2f", totalCredits));
            
            tableModel.addRow(rowData.toArray());
        }
        
        // 更新统计数据
        Map<String, Object> stats = new HashMap<>();
        stats.put("totalCount", totalCount);
        stats.put("passCount", passCount);
        stats.put("excellentCount", excellentCount);
        stats.put("range_90_100", range90_100);
        stats.put("range_80_89", range80_89);
        stats.put("range_70_79", range70_79);
        stats.put("range_60_69", range60_69);
        stats.put("range_0_59", range0_59);
        
        // 添加各科平均分数据
        stats.put("subjectAverages", subjectAverages);
        
        // 计算及格率和优秀率
        double passRate = totalCount > 0 ? (passCount * 100.0 / totalCount) : 0;
        double excellentRate = totalCount > 0 ? (excellentCount * 100.0 / totalCount) : 0;
        stats.put("passRate", passRate);
        stats.put("excellentRate", excellentRate);
        
        // 更新图表
        updateCharts(stats);
        
        System.out.println("Subject Averages:");
        subjectAverages.forEach((subject, avg) -> 
            System.out.println(subject + ": " + avg)
        );
        
        System.out.println("Finished loading class teacher data");
    }
    
    private List<StudentProfile> getClassStudents() {
        List<StudentProfile> students = new ArrayList<>();
        String sql = "SELECT u.username as student_no, u.name " +
                    "FROM students s " +
                    "JOIN users u ON s.user_id = u.id " +
                    "JOIN classes c ON s.class_id = c.id " +
                    "WHERE c.teacher_id = ? " +
                    "ORDER BY u.username";
        
        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, currentUser.getId());
            ResultSet rs = stmt.executeQuery();
            while (rs.next()) {
                StudentProfile student = new StudentProfile();
                student.setStudentNo(rs.getString("student_no"));
                student.setName(rs.getString("name"));
                students.add(student);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return students;
    }
    
    private void createNormalTable() {
        // 创建普通教师的表格列
        String[] columnNames = {
            "学号", "姓名", "班级", "科目", "成绩", "排名", "平均分", "考试类型", "考试日期"
        };
        
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        
        gradeTable = new JTable(tableModel);
        gradeTable.setFont(CONTENT_FONT);
        gradeTable.getTableHeader().setFont(TITLE_FONT);
        
        // 设置表格列宽
        TableColumnModel columnModel = gradeTable.getColumnModel();
        columnModel.getColumn(0).setPreferredWidth(100);  // 学号
        columnModel.getColumn(1).setPreferredWidth(80);   // 姓名
        columnModel.getColumn(2).setPreferredWidth(100);  // 班级
        columnModel.getColumn(3).setPreferredWidth(100);  // 科目
        columnModel.getColumn(4).setPreferredWidth(60);   // 成绩
        columnModel.getColumn(5).setPreferredWidth(60);   // 排名
        columnModel.getColumn(6).setPreferredWidth(60);   // 平均分
        columnModel.getColumn(7).setPreferredWidth(100);  // 考试类型
        columnModel.getColumn(8).setPreferredWidth(100);  // 考试日期
    }
    
    private void loadNormalData() {
        Map<String, Object> filters = new HashMap<>();
        filters.put("teacherId", currentUser.getId());
        
        if (classComboBox != null) {
            String selectedClass = (String) classComboBox.getSelectedItem();
            if (selectedClass != null && !selectedClass.equals("全部班级")) {
                filters.put("className", selectedClass);
            }
        }
        
        if (examTypeComboBox != null) {
            String selectedExamType = (String) examTypeComboBox.getSelectedItem();
            if (selectedExamType != null && !selectedExamType.equals("全部")) {
                filters.put("examType", selectedExamType);
            }
        }
        
        loadGradeData(filters);
    }
    
    private Map<String, Object> getFilters() {
        Map<String, Object> filters = new HashMap<>();
        
        // 获取班级ID
        String selectedClass = (String) classComboBox.getSelectedItem();
        if (selectedClass != null && !selectedClass.equals("全部班级")) {
            filters.put("className", selectedClass);
        }
        
        // 获取考试类型
        String examType = (String) examTypeComboBox.getSelectedItem();
        if (examType != null && !examType.equals("全部")) {
            filters.put("examType", examType);
        }
        
        // 获取考试日期
        if (examDateChooser.getDate() != null) {
            filters.put("examDate", new java.sql.Date(examDateChooser.getDate().getTime()));
        }
        
        // 获取搜索关键词
        String search = searchField.getText().trim();
        if (!search.isEmpty()) {
            filters.put("search", search);
        }
        
        // 如果是普通教师，添加教师ID筛选
        if (!isClassTeacher) {
            filters.put("teacherId", currentUser.getId());
        }
        
        if (isAdmin) {
            // 添加系部筛选
            String selectedDept = (String) departmentComboBox.getSelectedItem();
            if (selectedDept != null && !selectedDept.equals("全部系部")) {
                filters.put("departmentId", departmentIdMap.get(selectedDept));
            }
            
            // 添加专业筛选
            String selectedMajor = (String) majorComboBox.getSelectedItem();
            if (selectedMajor != null && !selectedMajor.equals("全部专业")) {
                filters.put("majorId", majorIdMap.get(selectedMajor));
            }
        }
        
        return filters;
    }


    private void loadDepartments() {
        try (Connection conn = DatabaseUtil.getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT * FROM departments ORDER BY dept_name")) {
            
            departmentComboBox.removeAllItems();
            departmentComboBox.addItem("全部系部");
            departmentIdMap = new HashMap<>();
            
            while (rs.next()) {
                String deptName = rs.getString("dept_name");
                int deptId = rs.getInt("id");
                departmentComboBox.addItem(deptName);
                departmentIdMap.put(deptName, deptId);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    
    private void loadMajors(int deptId) {
        String sql = "SELECT DISTINCT m.major_name " +
                    "FROM majors m " +
                    "JOIN departments d ON m.dept_code = d.dept_code " +
                    "WHERE d.dept_code = (SELECT dept_code FROM departments WHERE dept_name = ?) " +
                    "ORDER BY m.major_name";
        
        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            
            stmt.setString(1, (String) departmentComboBox.getSelectedItem());
            ResultSet rs = stmt.executeQuery();
            
            majorComboBox.removeAllItems();
            majorComboBox.addItem("全部专业");
            
            while (rs.next()) {
                majorComboBox.addItem(rs.getString("major_name"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    
    private JPanel createAdminPanel() {
        JPanel adminPanel = new JPanel(new BorderLayout(10, 10));
        adminPanel.setBorder(new EmptyBorder(10, 10, 10, 10));

        // 创建顶部筛选面板
        JPanel filterPanel = createFilterPanel();
        adminPanel.add(filterPanel, BorderLayout.NORTH);

        // 创建中间的表格面板，限制其高度
        createAdminTable();
        JScrollPane scrollPane = new JScrollPane(gradeTable);
        scrollPane.setPreferredSize(new Dimension(800, 300)); // 设置固定高度
        adminPanel.add(scrollPane, BorderLayout.CENTER);

        // 创建底部统计和图表面板
        JPanel bottomPanel = new JPanel(new BorderLayout());
        bottomPanel.setPreferredSize(new Dimension(800, 400)); // 设置固定高度
        
        // 创建统计面板
        statsPanel = createStatsPanel();
        bottomPanel.add(statsPanel, BorderLayout.NORTH);
        
        // 初始化图表面板
        chartPanel = new JPanel(new GridLayout(1, 2, 10, 0)); // 使用网格布局，1行2列
        chartPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
        
        // 创建饼图和柱状图面板
        pieChartPanel = createEmptyChartPanel();
        barChartPanel = createEmptyChartPanel();
        
        // 设置图表面板的大小
        pieChartPanel.setPreferredSize(new Dimension(380, 300));
        barChartPanel.setPreferredSize(new Dimension(380, 300));
        
        chartPanel.add(pieChartPanel);
        chartPanel.add(barChartPanel);
        
        bottomPanel.add(chartPanel, BorderLayout.CENTER);
        adminPanel.add(bottomPanel, BorderLayout.SOUTH);

        return adminPanel;
    }

    // 创建一个空的图表面板
    private ChartPanel createEmptyChartPanel() {
        DefaultPieDataset emptyDataset = new DefaultPieDataset();
        JFreeChart emptyChart = ChartFactory.createPieChart(
            "暂无数据",
            emptyDataset,
            true,
            true,
            false
        );
        return new ChartPanel(emptyChart);
    }

    private void loadGradeData(Map<String, Object> filters) {
        // 生成缓存key
        String cacheKey = generateCacheKey(filters);
        
        // 检查缓存
        if (gradeCache.containsKey(cacheKey)) {
            updateTableWithGrades(gradeCache.get(cacheKey));
            return;
        }
        
        // 如果缓存中没有，则从数据库加载
        List<Grade> grades = gradeService.getGrades(filters, "");
        gradeCache.put(cacheKey, grades);
        updateTableWithGrades(grades);
    }
    
    private void updateTableWithGrades(List<Grade> grades) {
        tableModel.setRowCount(0);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        
        // 使用 StringBuilder 优化字符串拼接
        for (Grade grade : grades) {
            Object[] rowData = {
                grade.getStudentNo(),
                grade.getStudentName(),
                grade.getClassName(),
                grade.getMajorName(),
                grade.getSubjectName(),
                String.format("%.1f", grade.getScore()),
                grade.getExamType(),
                sdf.format(grade.getExamDate()),
                grade.getRank()
            };
            tableModel.addRow(rowData);
        }
    }
    
    private void loadClasses(String majorName) {
        String sql = "SELECT DISTINCT c.class_name " +
                    "FROM classes c " +
                    "JOIN majors m ON c.major_code = m.major_code " +
                    "WHERE m.major_name = ? " +
                    "ORDER BY c.class_name";
        
        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            
            stmt.setString(1, majorName);
            ResultSet rs = stmt.executeQuery();
            
            classComboBox.removeAllItems();
            classComboBox.addItem("全部班级");
            
            while (rs.next()) {
                classComboBox.addItem(rs.getString("class_name"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    
    private String generateCacheKey(Map<String, Object> filters) {
        if (filters == null || filters.isEmpty()) {
            return "all";
        }
        
        StringBuilder key = new StringBuilder();
        // 按照键的字母顺序排序，确保相同的过滤条件生成相同的key
        TreeMap<String, Object> sortedFilters = new TreeMap<>(filters);
        
        for (Map.Entry<String, Object> entry : sortedFilters.entrySet()) {
            if (entry.getValue() != null) {
                key.append(entry.getKey())
                   .append("=")
                   .append(entry.getValue().toString())
                   .append(";");
            }
        }
        return key.toString();
    }

    private JPanel createFilterPanel() {
        JPanel filterPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        
        // 添加系部选择
        filterPanel.add(new JLabel("系部:"));
        departmentComboBox = new JComboBox<>();
        departmentComboBox.addItem("全部系部");
        departmentComboBox.setFont(CONTENT_FONT);
        filterPanel.add(departmentComboBox);
        
        // 添加专业选择
        filterPanel.add(new JLabel("专业:"));
        majorComboBox = new JComboBox<>();
        majorComboBox.addItem("全部专业");
        majorComboBox.setFont(CONTENT_FONT);
        filterPanel.add(majorComboBox);
        
        // 添加考试类型选择
        filterPanel.add(new JLabel("考试类型:"));
        examTypeComboBox = new JComboBox<>(new String[]{"全部", "期中考试", "期末考试", "单元测试"});
        examTypeComboBox.setFont(CONTENT_FONT);
        filterPanel.add(examTypeComboBox);
        
        // 添加班级选择
        filterPanel.add(new JLabel("班级:"));
        classComboBox = new JComboBox<>();
        classComboBox.addItem("全部班级");
        classComboBox.setFont(CONTENT_FONT);
        filterPanel.add(classComboBox);
        
        // 添加事件监听
        departmentComboBox.addActionListener(e -> {
            String selectedDept = (String) departmentComboBox.getSelectedItem();
            if (selectedDept != null && !selectedDept.equals("全部系部")) {
                int deptId = departmentIdMap.get(selectedDept);
                loadMajors(deptId);
            } else {
                majorComboBox.removeAllItems();
                majorComboBox.addItem("全部专业");
            }
            refreshData();
        });
        
        majorComboBox.addActionListener(e -> {
            String selectedMajor = (String) majorComboBox.getSelectedItem();
            if (selectedMajor != null && !selectedMajor.equals("全部专业")) {
                loadClasses(selectedMajor);
            } else {
                classComboBox.removeAllItems();
                classComboBox.addItem("全部班级");
            }
            refreshData();
        });
        
        classComboBox.addActionListener(e -> refreshData());
        examTypeComboBox.addActionListener(e -> refreshData());
        
        return filterPanel;
    }

    private JPanel createStatsPanel() {
        JPanel statsPanel = new JPanel(new GridLayout(1, 4, 10, 0));
        statsPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        
        // 添加统计标签
        totalStudentsLabel = new JLabel("总人数: 0人");
        averageScoreLabel = new JLabel("平均分: 0.00");
        passRateLabel = new JLabel("及格率: 0.00%");
        excellentRateLabel = new JLabel("优秀率: 0.00%");
        
        // 设置字体
        totalStudentsLabel.setFont(CONTENT_FONT);
        averageScoreLabel.setFont(CONTENT_FONT);
        passRateLabel.setFont(CONTENT_FONT);
        excellentRateLabel.setFont(CONTENT_FONT);
        
        statsPanel.add(totalStudentsLabel);
        statsPanel.add(averageScoreLabel);
        statsPanel.add(passRateLabel);
        statsPanel.add(excellentRateLabel);
        
        return statsPanel;
    }

    private void createAdminTable() {
        // 创建管理员视图的表格模型
        String[] columnNames = {"学号", "姓名", "班级", "专业", "课程", "成绩", "考试类型", "考试日期", "排名"};
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        
        gradeTable = new JTable(tableModel);
        gradeTable.setFont(CONTENT_FONT);
        gradeTable.getTableHeader().setFont(TITLE_FONT);
        gradeTable.setRowHeight(25);
        
        // 设置列宽
        TableColumnModel columnModel = gradeTable.getColumnModel();
        columnModel.getColumn(0).setPreferredWidth(80);   // 学号
        columnModel.getColumn(1).setPreferredWidth(60);   // 姓名
        columnModel.getColumn(2).setPreferredWidth(80);   // 班级
        columnModel.getColumn(3).setPreferredWidth(100);  // 专业
        columnModel.getColumn(4).setPreferredWidth(80);   // 课程
        columnModel.getColumn(5).setPreferredWidth(50);   // 成绩
        columnModel.getColumn(6).setPreferredWidth(70);   // 考试类型
        columnModel.getColumn(7).setPreferredWidth(80);   // 考试日期
        columnModel.getColumn(8).setPreferredWidth(50);   // 排名
        
        // 设置居中对齐
        DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
        centerRenderer.setHorizontalAlignment(JLabel.CENTER);
        for (int i = 0; i < gradeTable.getColumnCount(); i++) {
            gradeTable.getColumnModel().getColumn(i).setCellRenderer(centerRenderer);
        }
        
        // 设置表格选择模式
        gradeTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        gradeTable.setAutoCreateRowSorter(true);
        
        // 设置表头不可移动
        gradeTable.getTableHeader().setReorderingAllowed(false);
    }
} 